<template>
    <div id="detail">
        <div id="forum-detail">
            <div class="header" style="align-items: center">
                <img
                    :src="authorImage"
                    class="img"
                    @click="toPersonal"
                    style="cursor: pointer"
                />
                <div class="info">
                    <h3>{{ userInfoOfArticle.nickname || "" }}</h3>
                    <!-- <span>{{ opinionInfo.sig }}</span> -->
                </div>
                <div
                    class="like-reply"
                    style="margin-left: 20px"
                    :key="reloadKey"
                >
                    <i
                        class="like iconfont icon-xinaixin"
                        @click="guanzhu"
                        v-if="!isLiked"
                    ></i>
                    <i
                        class="like isLike iconfont icon-xinaixin"
                        @click="qxguanzhu"
                        v-if="isLiked"
                    ></i>
                    <!--点赞数-->
                    <span>{{ this.likesCount }}</span>
                </div>
            </div>
            <div class="content">
                <div class="content-header">
                    <h2 class="title">{{ opinionInfo.title }}</h2>
                    <h4 class="time">
                        {{ formatDate(opinionInfo.publishTime) }}
                    </h4>
                </div>
                <div class="des">
                    <span
                        class="dangerousHtml"
                        v-html="opinionInfo.content"
                    ></span>
                </div>
            </div>
            <article>
                <h2>留言</h2>
                <p>文明发言\(^o^)/~</p>
                <el-input
                    type="textarea"
                    :rows="2"
                    placeholder="请输入内容"
                    maxlength="100"
                    show-word-limit
                    v-model="msg"
                >
                </el-input>
                <el-button
                    class="button"
                    type="primary"
                    size="mini"
                    @click="messageReport"
                    >发表</el-button
                >
            </article>
        </div>
        <div class="message" :key="reloadKey">
            <ul v-if="messages.length !== 0">
                <li v-for="(item, index) in messages" :key="index">
                    <div class="top">
                        <img
                            :src="
                                item.headsculptureUrl
                                    ? item.headsculptureUrl
                                    : defaultImage
                            "
                            class="img"
                            @click="
                                toPersonal2(userInfoOfComment[index].serial)
                            "
                            style="cursor: pointer"
                        />
                        <div
                            class="name-time"
                            v-if="userInfoOfComment.length !== 0"
                        >
                            <!--用户名-->
                            <span>{{ userInfoOfComment[index].nickname }}</span>
                            <!--留言时间-->
                            <span>{{ formatDate(item.commentTime) }}</span>
                        </div>
                    </div>
                    <div class="message">
                        <!--留言内容-->
                        {{ item.content }}
                    </div>
                </li>
            </ul>
        </div>
        <div id="return" @click="returnlast">返 回</div>
    </div>
</template>

<script>
import qs from "qs";
export default {
    name: "ForumDetail",
    data() {
        return {
            reloadKey: 0,
            isLiked: false,
            userInfoOfArticle: {},
            opinionInfo: {},
            msg: "",
            messages: [],
            userInfoOfComment: [],
            isFollowEd: [],
            likesCount: "",
            authorImage: "/img/ttxbb.2670d53d.jpg",
            defaultImage: "/img/ttxbb.2670d53d.jpg",
            reloadKey: 0,
        };
    },
    methods: {
        // 处理时间
        formatDate(val) {
            let date = new Date(val),
                YY = date.getFullYear(),
                MM = date.getMonth() + 1,
                DD = date.getDate(),
                hh = date.getHours(),
                mm = date.getMinutes(),
                ss = date.getSeconds();

            hh < 10 && (hh = "0" + hh);
            mm < 10 && (mm = "0" + mm);
            ss < 10 && (ss = "0" + ss);

            return `${YY}-${MM}-${DD} ${hh}:${mm}:${ss}`;
        },
        // 留言
        messageReport() {
            if (!this.$store.state.userInfo.serial) {
                this.$message.warning("请先登录");
            } else {
                if (this.msg == "") {
                    this.$message.warning("内容不能为空");
                } else {
                    this.$axios({
                        method: "post",
                        url: "http://localhost:8081/ts/article/comment",
                        headers: { token: localStorage.getItem("token") || "" },
                        data: qs.stringify({
                            userId: this.$store.state.userInfo.serial,
                            articleId: this.$route.params.id,
                            content: this.msg,
                        }),
                    }).then((res) => {
                        this.$message.success("留言成功");
                        this.msg = "";

                        this.$axios({
                            method: "get",
                            url: `http://localhost:8081/ts/article/readarticle?articleId=${this.$route.params.id}`,
                            headers: {
                                token: localStorage.getItem("token") || "",
                            },
                        }).then((res) => {
                            this.messages = JSON.parse(
                                res.data.respData.allcomment
                            );
                            this.opinionInfo = JSON.parse(
                                res.data.respData.article
                            );
                            this.userInfoOfArticle = JSON.parse(
                                res.data.respData.userInfoOfArticle
                            );
                            this.userInfoOfComment = JSON.parse(
                                res.data.respData.userInfoOfComment
                            );
                            //循环将this.messages中的每一个对象中的headsculptureUrl替换为this.userInfoOfComment中对应serial的headsculptureUrl（如果存在的话，可能为空，为空则设置为defaultImage）,使用流操作
                            this.messages = this.messages.map((item) => {
                                //使用find函数将this.userInfoOfComment中对应serial的对象过滤出来
                                const userInfo = this.userInfoOfComment.find(
                                    (user) => user.serial === item.user_id
                                );
                                //如果userInfo存在，则将item中的headsculptureUrl替换为userInfo中的headsculptureUrl，否则替换为defaultImage
                                if (userInfo) {
                                    item.headsculptureUrl =
                                        userInfo.headsculptureUrl;
                                } else {
                                    item.headsculptureUrl = this.defaultImage;
                                }
                                return item;
                            });
                        });
                    });
                }
            }
        },
        // 获取留言
        getMessage() {
            this.$axios({
                method: "post",
                url: "/opinion/messages",
                data: {
                    _id: this.$route.params.id,
                },
            }).then((res) => {
                this.messages = res.data.message;
            });
        },
        returnlast() {
            this.$router.go(-1);
        },
        toPersonal() {
            this.$router.push(`/personal/${this.userInfoOfArticle.serial}`);
        },
        toPersonal2(serial) {
            this.$router.push(`/personal/${serial}`);
        },
        guanzhu() {
            if (this.$store.state.userInfo.serial) {
                this.$axios({
                    method: "get",
                    headers: { token: localStorage.getItem("token") || "" },
                    url: `http://localhost:8081/ts/article/like?articleId=${this.$route.params.id}&userId=${this.$store.state.userInfo.serial}`,
                }).then((res) => {
                    if (res.data.respCode === "200")
                        this.$message.success("喜欢成功");
                    this.$axios({
                        method: "get",
                        url: `http://localhost:8081/ts/article/readarticle?articleId=${this.$route.params.id}`,
                        headers: { token: localStorage.getItem("token") || "" },
                    }).then((res) => {
                        this.messages = JSON.parse(
                            res.data.respData.allcomment
                        );
                        this.opinionInfo = JSON.parse(
                            res.data.respData.article
                        );
                        this.userInfoOfArticle = JSON.parse(
                            res.data.respData.userInfoOfArticle
                        );
                        this.userInfoOfComment = JSON.parse(
                            res.data.respData.userInfoOfComment
                        );
                        console.log(res);
                        this.likesCount = res.data.respData.likesCount;
                        if (this.likesCount < 0) {
                            this.likesCount = 0;
                        }
                        this.isFollowEd = res.data.respData.isFollowed;
                        this.isLiked = res.data.respData.isliked === "1";
                    });
                    console.log(this.isFollowEd);
                    this.reloadKey++;
                });
            } else {
                this.$message.warning("暂未登录");
            }
        },
        qxguanzhu() {
            if (this.$store.state.userInfo.serial) {
                this.$axios({
                    method: "get",
                    headers: { token: localStorage.getItem("token") || "" },
                    url: `http://localhost:8081/ts/article/unlike?articleId=${this.$route.params.id}&userId=${this.$store.state.userInfo.serial}`,
                }).then((res) => {
                    if (res.data.respCode === "200")
                        this.$message.success("取消喜欢成功");
                    this.$axios({
                        method: "get",
                        url: `http://localhost:8081/ts/article/readarticle?articleId=${this.$route.params.id}`,
                        headers: { token: localStorage.getItem("token") || "" },
                    }).then((res) => {
                        this.messages = JSON.parse(
                            res.data.respData.allcomment
                        );
                        this.opinionInfo = JSON.parse(
                            res.data.respData.article
                        );
                        this.userInfoOfArticle = JSON.parse(
                            res.data.respData.userInfoOfArticle
                        );
                        this.userInfoOfComment = JSON.parse(
                            res.data.respData.userInfoOfComment
                        );
                        this.likesCount = res.data.respData.likesCount;
                        if (this.likesCount < 0) {
                            this.likesCount = 0;
                        }
                        this.isFollowEd = res.data.respData.isFollowed;
                        this.isLiked = res.data.respData.isliked === "1";
                        this.reloadKey++;
                    });
                });
            } else {
                this.$message.warning("暂未登录");
            }
        },
    },
    created() {
        if (!this.$store.state.userInfo.serial) {
            this.$message.warning("暂未登录");
            this.$router.push("/");
        }
        this.$axios({
            method: "get",
            url: `http://localhost:8081/ts/article/readarticle?articleId=${this.$route.params.id}`,
            headers: { token: localStorage.getItem("token") || "" },
        }).then((res) => {
            this.messages = JSON.parse(res.data.respData.allcomment);
            this.opinionInfo = JSON.parse(res.data.respData.article);
            this.userInfoOfArticle = JSON.parse(
                res.data.respData.userInfoOfArticle
            );

            if (this.userInfoOfArticle.headsculptureUrl) {
                this.authorImage = this.userInfoOfArticle.headsculptureUrl;
            }
            this.userInfoOfComment = JSON.parse(
                res.data.respData.userInfoOfComment
            );
            console.log(res.data.respData);
            this.isFollowEd = res.data.respData.isFollowed;
            this.likesCount = res.data.respData.likesCount;
            if (this.likesCount < 0) {
                this.likesCount = 0;
            }
            this.isLiked = res.data.respData.isliked === "1";

            //循环将this.messages中的每一个对象中的headsculptureUrl替换为this.userInfoOfComment中对应serial的headsculptureUrl（如果存在的话，可能为空，为空则设置为defaultImage）,使用流操作
            this.messages = this.messages.map((item) => {
                //使用find函数将this.userInfoOfComment中对应serial的对象过滤出来
                const userInfo = this.userInfoOfComment.find(
                    (user) => user.serial === item.user_id
                );
                //如果userInfo存在，则将item中的headsculptureUrl替换为userInfo中的headsculptureUrl，否则替换为defaultImage
                if (userInfo) {
                    item.headsculptureUrl = userInfo.headsculptureUrl;
                } else {
                    item.headsculptureUrl = this.defaultImage;
                }
                return item;
            });
        });
        console.log(this.isLiked);
    },
};
</script>

<style lang="less" scoped>
div.like-reply {
    i {
        cursor: pointer;
        font-size: 14px;
        color: #aaa;
    }

    i.isLike {
        color: #f30606;
    }

    span {
        display: inline-block;
        width: 43px;
        font-size: 12px;
        color: #aaa;
    }
}
#detail {
    position: relative;
    #forum-detail {
        box-sizing: border-box;
        width: 100%;
        box-shadow: 0 0 4px #ddd;
        background-color: #fff;
        padding: 15px;
        border-radius: 15px;
        .header {
            display: flex;
            margin-left: 60px;
            padding: 15px 0;
            .img {
                width: 50px;
                height: 50px;
                background-size: cover;
                background-position: center top;
                margin-right: 10px;
            }
            .info {
                display: flex;
                flex-direction: column;
                justify-content: space-around;
            }
        }
        .content {
            .content-header {
                position: relative;
                .title {
                    width: 400px;
                    height: 50px;
                    line-height: 50px;
                    text-align: center;
                    margin: 0 auto;
                    color: #a2c241;
                }
                .time {
                    position: absolute;
                    top: 40px;
                    right: 75px;
                }
            }
            .des {
                padding: 30px 60px;
                font-size: 16px;
                line-height: 25px;
            }
        }
        article {
            padding: 10px 60px;
            h2 {
                font-size: 20px;
                letter-spacing: 3px;
                line-height: 24px;
                border-left: 5px solid #a2c241;
                text-indent: 10px;
            }
            /deep/ textarea {
                min-height: 80px !important;
                color: #444;
                font-size: 14px;
                letter-spacing: 4px;
                line-height: 30px;
            }
            p {
                text-indent: 0.5em;
                color: #444;
                font-size: 14px;
                letter-spacing: 4px;
                line-height: 50px;
            }
            .button {
                margin-top: 15px;
            }
        }
    }
    .message {
        box-sizing: border-box;
        width: 100%;
        background-color: #fff;
        padding: 20px 75px;
        border-radius: 15px;
        margin-top: 15px;
        ul {
            li {
                padding-bottom: 5px;
                margin-bottom: 10px;
                border-bottom: 1px dashed #ddd;
                .top {
                    display: flex;
                    padding: 10px 0 0 0;
                    .img {
                        width: 40px;
                        height: 40px;
                        background-size: cover;
                        background-position: center top;
                        border-radius: 50%;
                    }
                    .name-time {
                        display: flex;
                        flex-direction: column;
                        font-size: 14px;

                        span:nth-child(1) {
                            color: #73b899;
                            margin-left: 10px;
                        }

                        span:nth-child(2) {
                            color: #aaa;
                            margin-left: 10px;
                            font-family: "Microsoft YaHei", "sans-serif";
                        }
                    }
                }

                .message {
                    color: #666;
                    letter-spacing: 2px;
                    margin-bottom: 3px;
                    word-break: break-word;
                    padding: 0 0 10px 0;
                    span {
                        color: #409eff;
                        margin-right: 5px;
                        font-size: 16px;
                    }
                }
            }
        }
    }
    #return {
        position: absolute;
        top: 5px;
        right: -45px;
        width: 30px;
        height: 50px;
        writing-mode: vertical-lr;
        line-height: 30px;
        text-align: center;
        background-color: #fff;
        border-radius: 15px;
        cursor: pointer;
        user-select: none;
        &:hover {
            background-color: #f5f5f1;
        }
    }
}
</style>
